package com.leo.snake;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class Food {
    BufferedImage img;
    int x;//自己的坐标
    int y;
    int maxX = 900 / 25;//最大x
    int maxY = 700 / 25;//最大y
    int WIGHT=1;//吃到这个食物的话应该增加多长
    Random r = new Random();

    /**
     * 初始化资源和位置
     *
     * @param snake
     */
    public Food(Snake snake) {
        try {
            img = ImageIO.read(Food.class.getResourceAsStream("/food.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        reset(snake.x, snake.y);
    }

    /**
     * 重新生成一个随机位置。不会与(x[i],y[i])重合
     *
     * @param x
     * @param y
     */
    public void reset(int[] x, int[] y) {
        this.x = r.nextInt(maxX);
        this.y = r.nextInt(maxY);
        if (x != null && y != null) {
            if (check(x, y)) reset(x, y);
        }
    }

    /**
     * 检测自身坐标是否与(x[i],y[i])重合
     *
     * @param x
     * @param y
     * @return
     */
    private boolean check(int[] x, int[] y) {
        for (int i = 0; i < x.length; i++) {
            if (x[i] == this.x && y[i] == this.y) return true;
        }
        return false;
    }

    /**
     * 画自己
     *
     * @param g
     */
    public void draw(Graphics g) {
        g.drawImage(img, x * 25, y * 25, null);
    }
}
